import router from '@ohos.router';
import prompt from '@ohos.prompt';
import GameModel from '../../../model/GameModel.js'
import GameStorageConstant from '../../../model/GameStorageConstant.js'
import RdbStoreModel from '../../../model/RdbStoreModel.js'

const TAG = '[gamePage]';

const WORD_CARD_BG ={
    NORMAL: 'box-select-normal',
    PASS: 'box-select-pass',
    ERROR: 'box-select-error'
};

const WORD_CARD_STYLE ={
    EASY: 'game-model-easy',
    MEDIUM: 'game-model-medium',
    DIFFICULTY: 'game-model-difficulty'
};

const FIGHT_RESULT_TEXT = {
    SUCCESS : '恭喜你，赢得挑战！',
    FAIL: '你输了，再接再厉！'
}

const WORD_CARD_TYPE =  {
    EASY : 9,
    MEDIUM: 16,
    DIFFICULTY: 25
}
export default {
    data: {
        title: "",
        curNickName: '',// 昵称
        startWordCard:0,// 开始数字
        errorCount:0, // 错误次数
        timeHandlerId: -1,// 定时器，
        minute:'00',
        second:'00',
        millisecond:'00',
        gameTime:0,// 游戏时间 用于比较用时
        wordCard:[],// 字卡列表
        selectedWordCard:[], // 已选的字卡列表,
        countDownList:[],// 倒计时动画
        isShowCountDown: true,// 是否显示倒计时动画视图
        curGameModel: 0,// 当前游戏模式
        wordCodeLen: WORD_CARD_TYPE.EASY, // 字卡长度,
        GameModel : new GameModel(),
        wordCodeStyle : WORD_CARD_STYLE.EASY, // 样式
        RdbStoreModel : new RdbStoreModel(),// 数据存储
        GameStorageConstant : new GameStorageConstant(),// 存储常量
        isFight: false,// 是否对战模式
        fightId: '',// 对战模式下存在对战ID
        deviceId: '',
        fightResultText:'',// 对战结果标题
        fightTimeStr:'',// 挑战者用时
        fightTime:0,
        isFightFinish: false,// 是否完成挑战
        mFirstTimeStr:'',
        mFirstTime:0,// 各模式的最少时间
        isShowMasking:true,// 是否显示游戏区域的蒙版
    },
    onInit() {
        this.initWordCode();
        this.title = this.$t('strings.world');
        this.refreshWordCode();
        this.countDownList = [
            {
                src: "/common/images/time_3.png",
            },
            {
                src: "/common/images/time_2.png",
            },
            {
                src: "/common/images/time_1.png",
            }
        ];
    },

    initWordCode(){
        // 获取上一个页面传递的参数
        this.isFight = router.getParams().is_fight;
        this.fightId = router.getParams().fight_id;
        this.deviceId = router.getParams().device_id;
        this.curNickName = router.getParams().nick_name;
        console.info("current nick name:" + this.curNickName);
        this.curGameModel = router.getParams().game_model;
        console.info("curGameModel:" + this.curGameModel);
        switch(this.curGameModel) {
            case this.GameModel.MODEL_EASY : {
                this.wordCodeStyle = WORD_CARD_STYLE.EASY;
                this.wordCodeLen = WORD_CARD_TYPE.EASY;
                break;
            }
            case this.GameModel.MODEL_MEDIUM : {
                this.wordCodeStyle = WORD_CARD_STYLE.MEDIUM;
                this.wordCodeLen = WORD_CARD_TYPE.MEDIUM;
                break;
            }
            case this.GameModel.MODEL_DIFFICULTY : {
                this.wordCodeStyle = WORD_CARD_STYLE.DIFFICULTY;
                this.wordCodeLen = WORD_CARD_TYPE.DIFFICULTY;
                break;
            }
            default :
            break;
        }

        let self = this;
        if(this.isFight) {
            // 对战
            this.RdbStoreModel.registerSyncListener((deviceId) => {
                self.RdbStoreModel.queryFightData(deviceId, self.curNickName, self.fightId, (fightResultSet)=>{
                    console.info(`${TAG} queryFightData ${JSON.stringify(fightResultSet)}`);
                    if (fightResultSet.length > 0) {
                        self.fightTime = fightResultSet[0].time;
                        self.fightTimeStr = fightResultSet[0].timeVal;
                    }
                    if (self.isFightFinish) {
                        if (self.gameTime < self.fightTime) {
                            self.fightResultText = FIGHT_RESULT_TEXT.SUCCESS;
                        } else {
                            self.fightResultText = FIGHT_RESULT_TEXT.FAIL;
                        }
                        // 当前用户已经完成挑战 关闭等待挑战结束弹窗
                        self.closeWaitGameDialog();
                        self.showFightGameOverDialog();
                    }
                });
            });
        } else {
            // 不是对战模式，则根据类型获取最少用时
            this.RdbStoreModel.queryFirstByModule(this.curNickName, this.curGameModel, (firstTime, firstTimeStr) => {
                self.mFirstTime = firstTime
                self.mFirstTimeStr = firstTimeStr;
            });
        }
    },

    /**
     * 重新挑战
     */
    onRestart() {
        if (this.isFight) {
            // 挑战模式启动挑战后不可重新挑战
            this.showToast('挑战已开始');
            return;
        }
        this.isShowMasking = true;
        this.isShowCountDown = true;
        this.startCountDown();
        this.closeGameOverDialog();
        this.resetTime();
        this.stopTime();
        this.errorCount = 0;
        this.startWordCard = 0;
        this.selectedWordCard = [];
        this.refreshWordCode();
    },

    refreshWordCode() {
        let length = this.wordCodeLen;
        this.wordCard = [];
        for(var i = 0; i < length; i++) {
            var wordCardInfo = {
                word: this.getWord(1, length),
                wordCardBg: WORD_CARD_BG.NORMAL
            }
            this.wordCard[i] = wordCardInfo;
        }
    },

    getWord(min, max) {
        var range = max - min;
        var rand = Math.random();
        var num = min + Math.round(rand * range); //四舍五入
        //  判断缓存字库中是否存在此数字
        if (this.isInArrayObject(this.wordCard, num)) {
            return this.getWord(min, max);
        }
        return num;
    },

    isInArrayObject(arr,value){
        for(var i = 0; i < arr.length; i++){
            if(value === arr[i].word){
                return true;
            }
        }
        return false;
    },

    isInArray(arr,value){
        for(var i = 0; i < arr.length; i++){
            if(value === arr[i]){
                return true;
            }
        }
        return false;
    },

    onWordCodeClick(word) {
        console.info("click word:" + word);
        if (this.timeHandlerId < 0) {
            // 启动计算器
            this.startTime();
        }
        // 判断是否为已选过的字卡,如果为已选过的字卡则不处理
        if (this.isInArray(this.selectedWordCard, word)) {
            this.errorCount++;
            return;
        }
        var newWordCard = this.startWordCard + 1;
        if (newWordCard === word) {
            // 正确
            this.startWordCard = newWordCard;
            this.selectedWordCard[this.selectedWordCard.length] = word;
            this.changeWordCodeBg(word, WORD_CARD_BG.PASS);
        } else {
            this.errorCount++;
            var self = this;
            this.changeWordCodeBg(word, WORD_CARD_BG.ERROR);
            setTimeout(function() {
                self.changeWordCodeBg(word, WORD_CARD_BG.NORMAL);
            }, 100);
        }
        // 判断挑战是否完成
        if (this.startWordCard === this.wordCard.length) {
            this.stopTime();
            // 根据类型区分数据存储，如果是单机则存储在本地，如果是对战则存储在分布式数据库
            if (this.isFight) {
                this.isFightFinish = true;
                this.saveFightGameInfo();
                // 判断挑战者是否已完成
                if (this.fightTimeStr.length > 0) {
                    if (this.gameTime < this.fightTime) {
                        this.fightResultText = FIGHT_RESULT_TEXT.SUCCESS;
                    } else {
                        this.fightResultText = FIGHT_RESULT_TEXT.FAIL;
                    }
                    this.showFightGameOverDialog();
                } else {
                    this.showWaitGameDialog();
                }
            } else {
                if (this.mFirstTimeStr.length <= 0 || this.gameTime < this.mFirstTime) {
                    this.mFirstTime = this.gameTime;
                    this.mFirstTimeStr = this.getGameTimeVal();
                }
                this.showGameOverDialog();
                this.saveGameInfo(this.curGameModel);
            }
        }
    },

    /**
     * 修改字卡的颜色
     * @param word 字卡
     * @param background 背景
     */
    changeWordCodeBg(word, background) {
        if (this.wordCard.length <= 0) {
            return;
        }
        console.info("changeWordCodeBg word:" + word + ";background:" + background);
        for (var i = 0; i < this.wordCard.length; i++) {
            // 修改字卡的背景颜色
            var temp = this.wordCard[i].word;
            if (temp === word) {
                this.wordCard[i].wordCardBg = background;
                console.info("changeWordCodeBg finish");
                break;
            }
        }
    },

    /**
     * 启动计时器
     */
    startTime() {
         var time = 0;
         this.gameTime = 0;
         var self = this;
         this.timeHandlerId = setInterval(function() {
             time++;
             self.gameTime++;
             self.millisecond = self.showNum(time % 100);
             self.second = self.showNum(parseInt(time / 63) % 60);
             self.minute = self.showNum(parseInt(time / 63 / 60) % 60);
         }, 10)
    },

    /**
     * 关闭计时器
     */
    stopTime() {
        if (this.timeHandlerId > 0) {
            clearInterval(this.timeHandlerId);
            this.timeHandlerId = -1;
        }
    },

    showNum(num){
        if (num < 10) {
            return '0' + num;
        }
        return num;
    },

    showGameOverDialog() {
        this.$element('gameOverDialog').show();
    },

    closeGameOverDialog() {
        this.$element('gameOverDialog').close();
    },

    showFightGameOverDialog() {
        this.$element('fightOverDialog').show();
    },

    closeFightGameOverDialog() {
        this.$element('fightOverDialog').close();
    },

    showWaitGameDialog() {
        this.$element('waitFightOverDialog').show();
    },

    closeWaitGameDialog() {
        this.$element('waitFightOverDialog').close();
    },

    onShow(){
        this.startCountDown();
    },

    /**
     * 启动倒计时动画
     */
    startCountDown() {
        this.$refs.countDown.start();
    },

    /**
     * 停止倒计时动画
     */
    stopCountDown() {
        this.$refs.countDown.stop();
    },

    /**
     * 监听停止倒计时动画的回调
     */
    onCountDownStop() {
        console.info("[CountDown] stop");
        this.isShowCountDown = false;
        this.isShowMasking = false;
    },

    /**
     *  重置时间
     */
    resetTime() {
        this.millisecond = "00";
        this.second = "00";
        this.minute = "00";
        this.gameTime = 0;
    },

    /**
     * 获取游戏时间值
     */
    getGameTimeVal() {
        return this.minute + ":" + this.second + "." + this.millisecond;
    },

    /**
     * 保存游戏数据
     */
    saveGameInfo(gameModel) {
        let valueBucket = {
            nick_name: this.curNickName,
            model:gameModel,
            time:this.gameTime,
            time_val:this.getGameTimeVal(),
        };
        console.info("save game info:" + JSON.stringify(valueBucket));
        let self = this;
        this.RdbStoreModel.insertValue(valueBucket, function(result){
            if (result != undefined && result == true) {
                self.showToast('游戏数据保存成功');
            } else {
                self.showToast('游戏数据保存失败');
            }
        });
    },

    /**
    * 保存对战游戏数据
    */
    saveFightGameInfo() {
        let valueBucket = {
            nick_name: this.curNickName,
            time:this.gameTime,
            time_val:this.getGameTimeVal(),
            fight_id: this.fightId
        };
        console.info(`${TAG} save game info to remote:${JSON.stringify(valueBucket)}`);
        let self = this;
        this.RdbStoreModel.insertFightValue(valueBucket, function(result){
            if (result != undefined && result == true) {
                self.showToast('对战游戏数据保存成功');
                // 将数据同步到其他的设备上
                self.RdbStoreModel.syncFightValue(function (syncResult) {
                    if (syncResult) {
                        console.info(`${TAG} syncFightValue finish`);
                        self.showToast('对战游戏数据同步成功');
                    } else {
                        self.showToast('对战游戏数据同步失败');
                    }
                });
            } else {
                self.showToast('对战游戏数据保存失败');
            }
        });
    },

    showToast(msg) {
        prompt.showToast({
            message: msg,
            duration: 3000
        });
    },

    onBack() {
        router.back();
    },

    onDestroy(){
        this.isFightFinish = false;
        this.resetTime();
        this.stopTime();
        this.stopCountDown();
        this.closeFightGameOverDialog();
        this.closeWaitGameDialog();
        this.RdbStoreModel.unregisterSyncListener();// 注销数据同步监听器
    }
}



